using Spring.Context;
using Spring.Context.Support;
using Spring.Objects.Factory.Support;
using Spring.Remoting;
using System;
namespace AppToolKit.Core.Context.Spring.AutoConstruction.Builder
{
	public abstract class ServerBuilderBase : IRemoteBusinessBuilder, IBusinessBuilder, IApplicationContextAware
	{
		protected ContextHelper helper_;
		private IApplicationContext appContext_;
		private AutoConstructionTypeLocation constructionLocation_;
		public AutoConstructionTypeLocation ConstructionLocation
		{
			get
			{
				if (this.constructionLocation_ == null)
				{
					this.constructionLocation_ = (AutoConstructionTypeLocation)this.helper_.GetObject(typeof(AutoConstructionTypeLocation));
				}
				return this.constructionLocation_;
			}
		}
		public IApplicationContext ApplicationContext
		{
			get
			{
				return this.appContext_;
			}
			set
			{
				this.appContext_ = value;
				this.helper_ = new ContextHelper(value);
			}
		}
		public void Export(Type businessType)
		{
			this.RegisterExport(businessType);
		}
		public void Register(Type businessType)
		{
			string businessName = this.GetBusinessName(businessType);
			if (!this.helper_.ContainsObjectDefine(businessName))
			{
				this.RegisterBusiness(businessType);
			}
		}
		protected abstract string GetBusinessName(Type type);
		public object GetObject(Type businessType)
		{
			this.Register(businessType);
			string businessName = this.GetBusinessName(businessType);
			return this.helper_.GetObject(businessName);
		}
		public abstract bool IsSupport(Type type);
		private void RegisterExport(Type businessType)
		{
			string businessName = this.GetBusinessName(businessType);
			DefaultListableObjectFactory defaultListableObjectFactory = (DefaultListableObjectFactory)((XmlApplicationContext)this.ApplicationContext).ObjectFactory;
			RootObjectDefinition rootObjectDefinition = new RootObjectDefinition(typeof(SaoExporter));
            rootObjectDefinition.IsSingleton = true; 
			rootObjectDefinition.PropertyValues.Add("TargetName", businessName);
            rootObjectDefinition.PropertyValues.Add("ServiceName", BusinessNameSymbol.GetExposeName(businessName));
			defaultListableObjectFactory.RegisterObjectDefinition(BusinessNameSymbol.GetSAOName(businessName), rootObjectDefinition);
			defaultListableObjectFactory.GetObject(BusinessNameSymbol.GetSAOName(businessName));
		}
		protected abstract void RegisterBusiness(Type businessType);
		protected void CheckType(Type implType, Type interfaceType)
		{
			if (!TypeHelper.IsInheritInterface(implType, interfaceType))
			{
				throw new AutoConstructionException(string.Format("{0}没有实现{1}", implType, interfaceType));
			}
		}
	}
}
